package org.jeecg.activiti.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ProcessDefinition;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.activiti.entity.ActHiModelFormData;
import org.jeecg.activiti.entity.ActKAppendFormData;
import org.jeecg.activiti.entity.ActKAppendFormDeployment;
import org.jeecg.activiti.entity.ActKHandleResult;
import org.jeecg.activiti.entity.ActKNode;
import org.jeecg.activiti.entity.ActKNodeDesign;
import org.jeecg.activiti.entity.ActKNodeFile;
import org.jeecg.activiti.entity.ActReModelExtend;
import org.jeecg.activiti.entity.ActReModelFormData;
import org.jeecg.activiti.entity.HistoricTaskVo;
import org.jeecg.activiti.service.IActHiModelFormDataService;
import org.jeecg.activiti.service.IActKAppendFormDataService;
import org.jeecg.activiti.service.IActKAppendFormDeploymentService;
import org.jeecg.activiti.service.IActKHandleResultService;
import org.jeecg.activiti.service.IActKNodeDesignService;
import org.jeecg.activiti.service.IActKNodeFileService;
import org.jeecg.activiti.service.IActKNodeService;
import org.jeecg.activiti.service.IActReModelExtendService;
import org.jeecg.activiti.service.IActReModelFormDataService;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping("/activiti/report")
@Api(tags = "流程报表数据")
public class ActReportController {

    @Autowired
    private IActHiModelFormDataService iActHiModelFormDataService;
    
    @Autowired
    private HistoryService historyService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private IActKNodeService iActKNodeService;

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private IActKHandleResultService iActKHandleResultService;

    @Autowired
    private IActKAppendFormDataService iActKAppendFormDataService;

    @Autowired
    private IActKAppendFormDeploymentService iActKAppendFormDeploymentService;

    @Autowired
    private IActKNodeFileService iActKNodeFileService;
    
    @Autowired
    private IActKNodeDesignService actKNodeDesignService;
    
    @Autowired
    private IActReModelExtendService actReModelExtendService;
    
    @Autowired
    private IActReModelFormDataService actReModelFormDataService;
    
    @GetMapping("/getReport")
    @ApiOperation(value = "获取报表", notes = "获取报表")
    public Result<String> getReport(@ApiParam(name="tableId", value="Online表ID", required = true) @RequestParam(name="tableId",required=true) String tableId){
    	List<ActReModelExtend> modelExts = actReModelExtendService.list(new QueryWrapper<ActReModelExtend>().eq("table_name", tableId));
    	for(ActReModelExtend modelExt : modelExts){
    		if(StringUtils.isNotEmpty(modelExt.getReportCode())){
    			return Result.OK("存在报表",modelExt.getReportCode());
    		}
    	}
    	return Result.OK("不存在报表",null);
    }
    
    @GetMapping("/getFlowinfo")
    @ApiOperation(value = "获取流程信息", notes = "获取流程信息")
    public Result<ActReModelFormData> getFlowinfo(@ApiParam(name="tableId", value="Online表ID", required = true) @RequestParam(name="tableId",required=true) String tableId,
    		@ApiParam(name="dataId", value="数据ID", required = true) @RequestParam(name="dataId",required=true) String dataId){
    	ActReModelFormData modelData = actReModelFormDataService.getOne(new QueryWrapper<ActReModelFormData>().eq("table_id", tableId).eq("data_id", dataId).eq("status", 2));
    	return Result.OK("成功",modelData);
    }

    @GetMapping("/getFormData")
    @ApiOperation(value = "根据流程实例ID查询流程历史表单数据", notes = "根据流程实例ID查询流程历史表单数据")
    public Map<String,List<Map<String,Object>>> getFormData(@ApiParam(name="processInstanceId", value="流程实例ID", required = true) @RequestParam(name="processInstanceId",required=true) String processInstanceId) {
        ActHiModelFormData actReModelFormData = iActHiModelFormDataService.getOne(new QueryWrapper<ActHiModelFormData>().eq("process_instance_id", processInstanceId));
        Map<String,Object> map = (Map<String,Object>) JSONObject.parseObject(actReModelFormData.getFormData());
        Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();  
        while(it.hasNext()){  
            Map.Entry<String, Object> entry = it.next();  
            if(entry.getKey().contains("$"))  
                it.remove();//使用迭代器的remove()方法删除元素  
        }
        List<Map<String,Object>> dataList = new ArrayList<>();
        dataList.add(map);
        Map<String,List<Map<String,Object>>> result = new HashMap<>();
        result.put("data", dataList);
        return result;
    }
    
    @ApiOperation(value="流程-流程流转历史", notes="流程流转历史")
    @RequestMapping(value = "/historicFlow", method = RequestMethod.GET)
    public Map<String,List<HistoricTaskVo>> historicFlow(@ApiParam(value="processInstanceId" ,name="流程实例Id") @RequestParam String processInstanceId,
    		@ApiParam(value="taskId" ,name="任务Id") @RequestParam(required = false,defaultValue = "") String taskId){
        List<HistoricTaskVo> list = new ArrayList<>();
        List<HistoricTaskInstance> taskList = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(processInstanceId).orderByHistoricTaskInstanceStartTime().desc().list();
        HistoricTaskInstance historicTaskInstance = historyService.createHistoricTaskInstanceQuery().taskId(taskId).singleResult();
        
        boolean isShowAppendForm = false;
        if (historicTaskInstance != null) {
        	ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(historicTaskInstance.getProcessDefinitionId()).singleResult();
            Model model = repositoryService.createModelQuery().modelKey(processDefinition.getKey()).singleResult();
            ActKNodeDesign actKNode = actKNodeDesignService.getOne(new QueryWrapper<ActKNodeDesign>()
                    .eq("node_id", historicTaskInstance.getTaskDefinitionKey())
                    .eq("model_id", model.getId()));
            if(actKNode != null && actKNode.getIsShowAppendForm()){
            	isShowAppendForm = actKNode.getIsShowAppendForm();
            }
        }
        for(HistoricTaskInstance e : taskList){
            HistoricTaskVo htv = new HistoricTaskVo(e);

            // 处理审批意见
            ActKHandleResult actKHandleResult = iActKHandleResultService.getOne(new QueryWrapper<ActKHandleResult>()
                    .eq("node_id", e.getTaskDefinitionKey())
                    .eq("process_instance_id", processInstanceId)
                    .eq("task_id", htv.getId())
                    .eq("execution_id", htv.getExecutionId()));
            if (actKHandleResult != null) {
                htv.setComment(actKHandleResult.getComment());
                htv.setFlagTxt(actKHandleResult.getResult());
            }
            if(isShowAppendForm){
            	// 查询附加表单数据
                ActKAppendFormDeployment actKAppendForm = iActKAppendFormDeploymentService.getOne(new QueryWrapper<ActKAppendFormDeployment>()
                        .eq("node_id", e.getTaskDefinitionKey()).eq("process_definition_id", e.getProcessDefinitionId()));
                
                // 如果该节点存在附加表单
                if (actKAppendForm != null) {
                    ActKAppendFormData actKAppendFormData = iActKAppendFormDataService.getOne(new QueryWrapper<ActKAppendFormData>()
                            .eq("node_id", e.getTaskDefinitionKey())
                            .eq("process_instance_id", processInstanceId)
                            .eq("task_id", htv.getId())
                            .eq("execution_id", htv.getExecutionId()));

                    htv.setActKAppendForm(actKAppendForm);
                    htv.setActKAppendFormData(actKAppendFormData);
                }
            }

            // 查询上传的附件
            List<ActKNodeFile> actKNodeFiles = iActKNodeFileService.list(new QueryWrapper<ActKNodeFile>()
                    .eq("node_id", e.getTaskDefinitionKey())
                    .eq("process_instance_id", processInstanceId)
                    .eq("task_id", htv.getId())
                    .eq("execution_id", htv.getExecutionId()));
            if (CollectionUtils.isNotEmpty(actKNodeFiles)) {
                htv.setActKNodeFiles(actKNodeFiles);
            }

            // 获取节点出去的线
            String nodeId = e.getTaskDefinitionKey();
            ActKNode actKNode = iActKNodeService.getOne(new QueryWrapper<ActKNode>()
                    .eq("node_id", nodeId).eq("process_definition_id", e.getProcessDefinitionId()));
            htv.setOutgoing(actKNode.getOutgoing());
            try{
            	htv.setAssignee(iSysUserService.getUserByName(htv.getAssignee()).getRealname());
            }catch (Exception ex) {
            	ex.printStackTrace();
			}

            list.add(htv);
        }
        Map<String,List<HistoricTaskVo>> result = new HashMap<>();
        result.put("data", list);

        return result;
    }
}
